<template>
  <div class="case-import-block">
    <a-form
      id="components-form-demo-validate-other"
      :form="form"
      v-bind="formItemLayout"
      @submit="handleSubmit"
    >
      <a-form-item label="案例类型">
        <a-select @change="handleSelectChange"
                  v-decorator="[
          'caseType',
          { initialValue: '故障案例',
            rules: [{ required: true, message: '请选择案例类型' }] },
        ]"
                  placeholder="请选择案例类型"
        >
          <a-select-option value="故障案例">
            故障案例
          </a-select-option>
          <a-select-option value="调试案例">
            调试案例
          </a-select-option>
          <a-select-option value="工艺案例">
            工艺案例
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item
        :label-col="formItemLayout.labelCol"
        :wrapper-col="formItemLayout.wrapperCol"
        label="案例名称"
      >
        <a-input
          v-decorator="[
          'caseName',
          { rules: [{ required: true, pattern: /\S/, message: '内容不能为空' }] },
        ]"
          placeholder="请输入" autoComplete="off"
        />
      </a-form-item>
      <a-form-item
        :label-col="formItemLayout.labelCol"
        :wrapper-col="formItemLayout.wrapperCol"
        :label="caseType==='故障案例' ? '故障代码' : '适用范围'"
      >
        <a-input
          v-decorator="[
          'caseCode',
          { rules: [{ required: true, pattern: /\S/, message: '内容不能为空' }] },
        ]"
          placeholder="请输入" autoComplete="off"
        />
      </a-form-item>
      <a-form-item
        :label-col="formItemLayout.labelCol"
        :wrapper-col="formItemLayout.wrapperCol"
        :label="caseType==='故障案例' ? '相关原因' : caseType==='调试案例' ? '调试目标' : '工艺目标'"
      >
        <a-textarea
          v-decorator="[
          'caseReason',
          { rules: [{ required: true, pattern: /\S/, message: '请输入相关原因' }] },
        ]"
          placeholder="请输入" autoComplete="off" style="resize: none"
        />
      </a-form-item>
      <a-row  v-for="(item, index) in newSolutionList" :key="item.id">
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="解决方案"
        >
          <a-textarea
            v-decorator="[`solutionContent[${index}].solution`,
          { rules: [{ required: true, pattern: /\S/, message: '请输入解决方案' }] },
        ]"
            placeholder="请输入解决方案" autoComplete="off" style="resize: none"
          />
        </a-form-item>
        <div class="upload-container" @click.prevent="updateFileIndex(index)">
          <a-upload
            :action="item.action"
            name="files"
            list-type="picture-card"
            :file-list="item.fileList"
            @preview="handlePreview"
            @change="handleChange"
          >
            <div v-if="item.fileList.length < 5">
              <a-icon type="plus"/>
              <div class="ant-upload-text">图 片</div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
          <span class="case-solution-delete" @click="deleteContent(item.id)">
            <a-icon type="close-circle" />
          </span>
        </div>
      </a-row>
      <a-form-item :wrapper-col="{ span: 12, offset: 2 }">
        <a-button type="primary" @click="addSingleSolution()">添加解决方案</a-button>
      </a-form-item>

      <a-form-item :wrapper-col="{ span: 16, offset: 0 }" label="案例标签">
        <!--<div :style="{ borderBottom: '1px solid #E9E9E9' }">
          <a-checkbox :indeterminate="indeterminate" :checked="checkAll" @change="onCheckAllChange">
            全 选
          </a-checkbox>
        </div>-->
        <a-checkbox-group v-model="checkedList" :options="tagOptions" @change="onChange" />
      </a-form-item>
      <a-form-item :wrapper-col="{ span: 12, offset: 2 }">
        <a-button type="primary" @click="addTags()">添加标签</a-button>
      </a-form-item>
      <a-form-item :wrapper-col="{ span: 12, offset: 6 }">
        <a-button type="primary" html-type="submit"
                  class="case-import-submit" :disabled="isDisabled">
          提 交
        </a-button>
      </a-form-item>
    </a-form>
    <a-modal title="添加标签" okText="确定" cancelText="取消" :visible="tagModel"
             @ok="handleAddTag" @cancel="handleTagCancel">
      <a-form layout='vertical' :form="mendForm">
        <a-form-item label='请添加标签'>
          <a-input
            type='text' style="resize: none"
            v-decorator="['tag',
              {
                rules: [{ required: true, pattern: /\S/, message: '请输入!' }],
              }
            ]"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
  import GLOBAL from '@/api/global_variable'
  import api from '@/server/userConfig';
  import TagContainer from './tagContainer';
  let tagOptions = JSON.parse(localStorage.getItem('tags'));
  const defaultCheckedList = [];
  export default {
    name: 'CaseImport',
    components: {
      TagContainer
    },
    props: {
      userName: String
    },
    data () {
      return {
        fileIndex: 0,
        previewVisible: false,
        tagList: [],
        previewImage: '',
        formItemLayout: {
          labelCol: { span: 2 },
          wrapperCol: { span: 14 },
        },
        solutionList: [{
          id: 1,
          fileList: [],
        }],
        count: 0,
        isDisabled: false,
        caseType: '故障案例',
        checkedList: defaultCheckedList,
        indeterminate: true,
        checkAll: false,
        tagOptions: tagOptions,
        tagModel: false,
        mendForm: this.$form.createForm(this, { name: 'mend_form' }),
      }
    },
    computed: {
      newSolutionList: function () {
        const { hncWebIp } = GLOBAL;
        for (let i = 0; i < this.solutionList.length; i++) {
          this.solutionList[i].action = hncWebIp+"/uploadSolutionPicture.action?pictureType="+this.solutionList[i].id+
            "&pictureNumber="+this.solutionList[i].id;
        }
        return this.solutionList;
      }
    },
    beforeCreate () {
      this.form = this.$form.createForm(this, { name: 'validate_other' });
    },
    methods: {
      mounted () {
        this.tags = this.plainOptions;
      },
      onChange (checkedList) {
        this.indeterminate = !!checkedList.length && checkedList.length < tagOptions.length;
        this.checkAll = checkedList.length === tagOptions.length;
        this.tagList = [...checkedList];
      },
      onCheckAllChange (e) {
        Object.assign(this, {
          checkedList: e.target.checked ? tagOptions : [],
          indeterminate: false,
          checkAll: e.target.checked,
        });
      },
      // 添加标签;
      addTags () {
        this.tagModel = true;
      },
      handleAddTag () {
        const form = this.mendForm;
        form.validateFields((err, values) => {
          if (err) { return; }
          const inputValue = values.tag;
          if (inputValue && tagOptions.indexOf(inputValue) === -1) {
            this.tagOptions = [...tagOptions, inputValue];
          }
          localStorage.setItem('tags', JSON.stringify(this.tagOptions));
          form.resetFields();
          this.tagModel = false;
        });
      },
      handleTagCancel () {
        this.tagModel = false;
      },
      handleSelectChange (value) {
        this.caseType = value;
      },
      // 获取上传图片的索引;
      updateFileIndex (index) {
        this.fileIndex = index
      },
      getChildTag (tags) {
        this.tags = tags;
      },
      handleSubmit (e) {
        e.preventDefault();
        this.form.validateFields( async (err, values) => {
          if (!err) {
            // console.log(values);
            // console.log(this.solutionList);
            // console.log(this.tags);
            let solution = [];
            let solutionList = this.solutionList;
            const solutionListLength = solutionList.length;
            for (let i = 0; i < solutionListLength; i++) {
              let idArr = [];
              let idStr = '';
              if (solutionList[i].fileList.length > 0) {
                const singleSolutionList = solutionList[i].fileList;
                const singleSolutionListLength = singleSolutionList.length;
                for (let j = 0; j < singleSolutionListLength; j++) {
                  idArr.push(singleSolutionList[j].id);
                  idStr = idArr.join(',');
                }
              }
              solutionList[i].idStr = idStr;
              solution.push({
                item: values.solutionContent[i].solution,
                step: i,
                pictureId: solutionList[i].idStr || 0
              });
            }
            let submitCaseData = {};
            submitCaseData.caseType = values.caseType;
            submitCaseData.caseName = values.caseName;
            submitCaseData.situation = values.caseCode;
            submitCaseData.description = values.caseReason;
            submitCaseData.username = this.userName;
            submitCaseData.caseTag = this.tagList;
            submitCaseData.solution = solution;
            submitCaseData.id = 0;
            const jsonSubmitCaseData = JSON.stringify(submitCaseData);
            console.log(jsonSubmitCaseData);
            const res = await api.reqCaseImport(jsonSubmitCaseData);
            console.log(res);
            if (res.MsgCode === 0) {
              this.$Modal.success({
                title: '',
                content: '录入成功!',
                okText: '确定'
              });
              this.isDisabled = true;
            }
          }
        });
      },
      // 添加一条解决方案;
      addSingleSolution () {
        this.count = this.count + 10;
        this.$set(this.solutionList, this.solutionList.length, {
          id: this.count,
          fileList: []
        })
        // this.solutionList.push({
        //   id: this.count,
        //   fileList: []
        // })
      },
      handleCancel () {
        this.previewVisible = false;
      },
      async handlePreview (file) {
        console.log(file);
        if (!file.url && !file.preview) {
          file.preview = await getBase64(file.originFileObj);
        }
        this.previewImage = file.url || file.preview;
        this.previewVisible = true;
      },
      handleChange ({file, fileList}) {
        if (file.status === 'uploading') {
          this.solutionList[this.fileIndex].fileList = fileList;
        }
        else if (file.status === 'done') {
          this.solutionList[this.fileIndex].fileList = fileList;
          file = fileList[fileList.length - 1];
          // 取出响应数据中的图片文件名和url
          const { id, url, pictureType } = file.response.Data[0];
          // 保存到上传的file对象
          file.id = id;
          file.pictureType = pictureType;
          file.url = GLOBAL.imgDownUrl + url;
          //console.log(file);
          //console.log(fileList);
          //console.log(this.solutionList);
        } else if (file.status === 'removed') {
          this.$Modal.confirm({
            title: '确定删除此图片吗?',
            content: '',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk: async () => {
              const result = await api.reqDeleteSingleImg({id: file.id});
              console.log(result);
              if (result.MsgCode === 0) {
                this.$message.success('删除成功!');
              }
              this.solutionList[this.fileIndex].fileList = fileList;
              //console.log(this.solutionList);
            },
            onCancel () {}
          });
        }
      },
      // 删除一条大的解决方案;
      deleteContent (id) {
        this.$Modal.confirm({
          title: '确定删除此条解决方案吗?',
          content: '',
          okText: '确定',
          okType: 'danger',
          cancelText: '取消',
          onOk: async () => {
            let idArr = [];
            let idStr = '';
            const solutionListLength = this.solutionList.length;
            for (let i = 0; i < solutionListLength; i++) {
              if (this.solutionList[i].id === id) {
                const singleSolutionList = [...this.solutionList[i].fileList];
                console.log(singleSolutionList);
                if (singleSolutionList.length > 0) {
                  for (let j = 0; j < singleSolutionList.length; j++) {
                    idArr.push(singleSolutionList[j].id);
                  }
                }
              }
            }
            if (idArr.length > 0) {
              idStr = idArr.join(',');
            }
            for (let i = 0; i < this.solutionList.length; i++) {
              if (this.solutionList.length <= 1) {
                this.$message.info('请至少保留一条解决方案');
                return;
              }
              if (this.solutionList[i].id === id) {
                this.solutionList.splice(i, 1);
              }
            }
            // 删除大的解决方案连同图片;
            const res = await api.reqDeleteCaseGroup({idStr: idStr});
            //console.log(res);
            if (res.MsgCode === 0) {
              this.$message.success('删除成功!');
            }
            console.log(this.solutionList);
          },
          onCancel () {}
        });
      }
    }
  }
</script>

<style scoped="scoped">
  @import "./style.css";
</style>
